package com.skanda.sys.componnet;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DistributedLock {
    @Resource
    private RedisTemplate<String, Boolean> redisTemplate;

    public boolean lock(String key,String value){
        Boolean ret = false;
        //通过redis setNX,加锁;
        ret = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.setNX(key.getBytes(),value.getBytes());
            }
        });
        //设置超时时间,防止永久被锁
        if(ret){
            redisTemplate.expire(key,30l, TimeUnit.SECONDS);
        }
        return ret;
    }
    public boolean unLock(String key){
        return redisTemplate.delete(key);
    }
}
